
'use strict'

const Service = require('egg').Service

class BillService extends Service {
    // 有关于账单的数据库操作


    // 获取账单列表
    async list(id) {
        const { ctx, app } = this

        // 账单id、账单类型（1为支出，2为收入）、金额、时间戳、具体类型的id（注意对上类型那张表）、类型名称、备注 
        const QUERY_STR = 'id, pay_type, amount, date, type_id, type_name, remark'
        let sql = `select ${QUERY_STR} from bill where user_id = ${id}`

        try {
            // 执行 sql 语句
            const result = await app.mysql.query(sql)
            return result


        } catch (error) {
            console.log(error);
            return null
        }

    }


    // 查询某个账单
    async findBill(id, user_id) {
        const { app } = this
        try {
            const QUERY_STR = 'id, pay_type, amount, date, type_id, type_name, remark'
            let sql = `select ${QUERY_STR} from bill where id = ${id} and user_id = ${user_id}`
            const result = await app.mysql.query(sql)
            console.log('2222', result);
            return result
        } catch (error) {
            console.log('查询某个账单出错', error);
            return
        }
    }

    // 查询总收入/总支出
    async findAll(pay_type, user_id) {
        const { app } = this
        try {
            const QUERY_STR = 'id, pay_type, amount, date, type_id, type_name'
            let sql = `select ${QUERY_STR} from bill where user_id = ${user_id} and pay_type = ${pay_type}`
            const result = await app.mysql.query(sql)
            console.log('查询总收入/总支出数据', result);
            return result

        } catch (error) {
            console.log('查询总数据失败', error);
            return
        }
    }


    // 创建一个新账单
    async addNewBill(params){
        const {app} = this
        try{
            const result = await app.mysql.insert('bill',params)
            console.log('创建新账单的数据库操作',result);
            return result
        }catch(error){
            console.log('创建新账单失败',error);
            return
        }
    }


    // 删除一条账单
    async deleteOneBill(id,user_id){
        const {app} = this

        try{

            let sql = `DELETE FROM bill WHERE id = ${id} and user_id = ${user_id} `

            const result = await app.mysql.query(sql)
            console.log('删除账单的数据库操作返回值',result);
            return result
        }catch(error){
            console.log('删除账单的数据库环节出错',error);
            return
        }
    }

    // 

}

module.exports = BillService